package com.micromall.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.micromall.common.exception.BusiException;
import com.micromall.common.payment.ISPaymentRequest;
import com.micromall.common.utils.*;
import com.micromall.model.*;
import com.micromall.mapper.BusiOrderMapper;
import com.micromall.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.micromall.service.strategy.IDiscountStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author Dante Fung
 * @since 2017-07-26
 */
@Service
public class BusiOrderServiceImpl extends ServiceImpl<BusiOrderMapper, BusiOrder> implements IBusiOrderService {

    private static final Logger logger = LoggerFactory.getLogger(BusiOrderServiceImpl.class);

    @Autowired
    private IBusiCartService busiCartService;
    @Autowired
    private IBusiCartDetailItemService busiCartDetailItemService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IBusiOrderItemService busiOrderItemService;
    @Autowired
    private IAlRegionService alRegionService;
    @Autowired
    private IBusiProductService busiProductService;
    @Autowired
    private IBusiCategroyService categroyService;
    @Autowired
    private IBusiProdCategoryService prodCategoryService;
    @Autowired
    private IDiscountStrategy discountStrategy;

    @Override
    public String genOrderByCartId(String cartId, Map<String, String> params) {
        String from = params.get("from");
        String receiverName = params.get("receiverName");
        String phoneNo = params.get("phoneNo");
        String areaId = params.get("areaId");
        String address = params.get("address");
        String cartItemIds = params.get("cartItemIds");

        String requestBody = null;
        if (StringUtils.isBlank(cartId)) {
            if (logger.isDebugEnabled()) {
                logger.error("From:[{}]-操作失败!原因:[购物车ID为空!]", from);
            }
            throw new BusiException(String.format("From:[%s]操作失败!原因:[购物车ID为空!]", from));
        }

        if (!StringUtils.isNotBlank(cartItemIds)) {
            if (logger.isDebugEnabled()) {
                logger.error("From:[{}]-操作失败!原因:[购物车明细项ID为空!]", from);
            }
            throw new BusiException(String.format("From:[%s]操作失败!原因:[购物车明细项ID为空!]", from));
        }

        // 1、查询出有效的购物车
//        BusiCart busiCart = busiCartService.selectById(cartId);
        EntityWrapper<BusiCart> cartWrapper = new EntityWrapper<BusiCart>();
        BusiCart cartQuery = new BusiCart();
        cartQuery.setId(cartId);
        cartQuery.setDataStatus(Dict.YesOrNo.Yes.getCode());
        cartWrapper.setEntity(cartQuery);
        List<BusiCart> busiCarts = busiCartService.selectList(cartWrapper);
        BusiCart busiCart = null;
        if (null != busiCarts && !busiCarts.isEmpty()) {
            busiCart = busiCarts.get(0);
        }
        // 2、查询出购物车下的所有有效购物车明细
        EntityWrapper<BusiCartDetailItem> ew = new EntityWrapper<>();
        BusiCartDetailItem cartDetailItemQuery = new BusiCartDetailItem();
        List<BusiCartDetailItem> cartDetailItems = new ArrayList<>();
        String[] ids = cartItemIds.split(",");
        for (String id : ids) {
            cartDetailItemQuery.setId(id);
            BusiCartDetailItem cartItem = busiCartDetailItemService.selectById(cartDetailItemQuery);
            cartDetailItems.add(cartItem);
//            cartDetailItemQuery.setCartId(cartId);
//            List<BusiCartDetailItem> list = busiCartDetailItemService.selectList(ew);
            /*if (null != list && !list.isEmpty()) {
                BusiCartDetailItem cartItem = list.get(0);
                cartDetailItems.add(cartItem);
            }*/
        }
//        cartDetailItemQuery.setStandy4(Dict.BusiCaer.CartItemStatusCode.PREPARE.getCode());
        // 2、封装订单对象及订单项
        if (null != busiCart) {
            BusiOrder busiOrder = new BusiOrder();
            String sql = "SELECT (SEQ_BUSI_ORDER.NEXTVAL) ID FROM DUAL";
            Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
            Object id = resultMap.get("id");
            busiOrder.setId(id.toString());
            busiOrder.setCreateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            busiOrder.setCreator("");
            MakeOrderNum makeOrderNum = MakeOrderNum.getMakeOrderNum();
            String orderNo = makeOrderNum.makeOrderNum(null);
            busiOrder.setPayStatus(Dict.BusiOrder.PayStatus.TOPAY.getCode());
            busiOrder.setOrderNo(orderNo);
            busiOrder.setCreatorName(receiverName);
            busiOrder.setCreatorCode(receiverName);
            busiOrder.setDataFrom("system");// TODO: 重构到字典类中.
            busiOrder.setCreateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            busiOrder.setUpdateaTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
            busiOrder.setUpdator("");
            busiOrder.setMemberNo("WS" + phoneNo);
            String fullAddress = alRegionService.getFullAddress(areaId, address);
            busiOrder.setAddress1(fullAddress);
            busiOrder.setAddress2(address);
            busiOrder.setAreaId(areaId);
            busiOrder.setReceiver(receiverName);
            busiOrder.setRecPhone(phoneNo);
            // 检测是否有折扣.
            busiOrder.setTotalAmount(busiCart.getTotalAmount());
            String discountPrice = null;
            Map<String, String> mapdto = discountStrategy.doDiscount("WS" + phoneNo, busiCart.getTotalAmount());
            discountPrice = mapdto.get("discountPrice");
            String disType = mapdto.get("disType");
            busiOrder.setStandy2(disType);
            if (StringUtils.isBlank(discountPrice)) {
                busiOrder.setStandy1(busiCart.getTotalAmount());
            } else {
                discountPrice = Math.round(Double.valueOf(discountPrice))+"";
                busiOrder.setStandy1(discountPrice);
            }
            busiOrder.setDataStatus(Dict.YesOrNo.Yes.getCode());

            boolean flag = this.insert(busiOrder);
//            List<BusiCartDetailItem> cartDetailItemListToUpdate = new ArrayList();
            String productName = null;
            if (flag) {
                List<BusiOrderItem> orderlistTosave = new ArrayList<>();
                BusiOrderItem orderItem = null;
                for (BusiCartDetailItem detailIem : cartDetailItems) {
                    if (StringUtils.isBlank(productName)) {
                        productName = detailIem.getProdName() + "等";
                    }
                    orderItem = new BusiOrderItem();
                    String idSql = "SELECT (SEQ_BUSI_ORDER_ITEM.NEXTVAL) ITEMID FROM DUAL";
                    Map<String, Object> orderItemIdResultMap = jdbcTemplate.queryForMap(idSql);
                    Object itemId = orderItemIdResultMap.get("itemid");
//                    orderItem.setStandy1(detailIem.getStandy1());
//                    orderItem.setStandy2(detailIem.getStandy2());
                    orderItem.setStandy3(Dict.YesOrNo.Yes.getCode());
                    BeanUtils.copy(detailIem, orderItem);
//                    detailIem.setStandy3((Dict.YesOrNo.No.getCode())); // 将备用字段3作为数据是否有效的状态位,Y 有效，N 无效
                    detailIem.setStandy4(Dict.BusiCaer.CartItemStatusCode.FINISH.getCode());
                    orderItem.setOrderId(busiOrder.getId());
                    orderItem.setId(itemId.toString());
                    orderlistTosave.add(orderItem);
//                    cartDetailItemListToUpdate.add(detailIem);
                    busiOrderItemService.insert(orderItem);
                    busiCartDetailItemService.updateById(detailIem);
                }
               /* boolean sOrf = busiOrderItemService.insertBatch(orderlistTosave);
                if (!sOrf) {
                    if (logger.isDebugEnabled()) {
                        logger.info("From:[{}]-[订单明细批量保存失败!]");
                    }
                    throw new BusiException(String.format("From:[%s]-订单明细批量保存失败!", from));
                }*/
            } else { // 如果新增订单失败，则订单明细也不存在.
                if (logger.isDebugEnabled()) {
                    logger.info("From:[Cart]-[订单生成失败!]");
                }
                throw new BusiException(String.format("From:[%s]-[订单生成失败!]", from));
            }

            // 3、修改购物车及购物车明细项数据状态为'N',新增订单及订单项数据.
            // 3.1、将购物车的总计置为0
            busiCart.setTotalAmount("0");
            busiCartService.updateById(busiCart);
            // 3.2、修改购物车明细项的状态为'N'
//            busiCartDetailItemService.updateBatchById(cartDetailItemListToUpdate);
            requestBody = ISPaymentRequest.genPayRequestMessage(orderNo, productName,"WS"+phoneNo, busiOrder.getStandy1());
            logger.info(String.format("生成的目标报文为:", requestBody));
        }
        return requestBody;
    }


    public String genOrderByProductId(String productId, Map<String, String> params) {
        String receiverName = params.get("receiverName");
        String sum = params.get("sum");
        String phoneNo = params.get("phoneNo");
        String areaId = params.get("areaId");
        String address = params.get("address");
        if (StringUtils.isBlank("productId")) {
            throw new RuntimeException("From:[productDetail]-[操作失败!][原因:产品ID为空!]");
        }
        // 1、通过产品ID查询出产品对象
        BusiProduct busiProductQuery = new BusiProduct();
        busiProductQuery.setId(productId);
        BusiProduct busiProduct = busiProductService.selectById(busiProductQuery);
        // 2、查询出该产品的分类.
        EntityWrapper<BusiProdCategory> ew = new EntityWrapper<BusiProdCategory>();
        BusiProdCategory busiProdCategoryQuery = new BusiProdCategory();
        busiProdCategoryQuery.setProdId(productId);
        // @TODO 目前认为就是 类别 - 产品  一对多.
        List<BusiProdCategory> busiProdCategories = prodCategoryService.selectList(ew);
        BusiProdCategory busiProdCategory = null;
        if (!busiProdCategories.isEmpty()) {
            busiProdCategory = busiProdCategories.get(1);
        }
        String categoryId = null;
        if (null != busiProdCategory) {
            categoryId = busiProdCategory.getCategoryId();
        }
        EntityWrapper<BusiCategroy> ew2 = new EntityWrapper<BusiCategroy>();
        BusiCategroy busiCategroyQuery = new BusiCategroy();
        busiCategroyQuery.setId(categoryId);
        List<BusiCategroy> busiCategroys = categroyService.selectList(ew2);
        BusiCategroy category = null;
        if (!busiCategroys.isEmpty()) {
            category = busiCategroys.get(0);
        }
        // 3、根据该产品的信息生成订单及订单项
        String sql = "SELECT (SEQ_BUSI_ORDER.NEXTVAL) ID FROM DUAL";
        Map<String, Object> resultMap = jdbcTemplate.queryForMap(sql);
        Object id = resultMap.get("id");
        BusiOrder order = new BusiOrder();
        order.setId(id.toString());
        order.setCreatorCode(receiverName);
        order.setCreator("");
        order.setReceiver(receiverName);
        order.setDataStatus(Dict.YesOrNo.Yes.getCode());
        order.setDataFrom("system");
        order.setPayStatus(Dict.BusiOrder.PayStatus.TOPAY.getCode());
        order.setCreateTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        order.setUpdateaTime(DateUtil.convertDateToStr(new Date(), DateUtil.DEFAULT_DATE_FORMAT));
        order.setUpdator("");
        order.setMemberNo("WS" + phoneNo);
        order.setAreaId(areaId);
        order.setRecPhone(phoneNo);
        order.setCreatorName(receiverName);
        String totalAmount = new BigDecimal(busiProduct.getPrice())
                .multiply(new BigDecimal(sum))
                .multiply(new BigDecimal(busiProduct.getDiscount()))
                .toString();
        order.setTotalAmount(totalAmount);
        Map<String, String> mapdto = discountStrategy.doDiscount("WS" + phoneNo, totalAmount);
        String discountPrice = mapdto.get("discountPrice");
        String disType = mapdto.get("disType");
        order.setStandy2(disType);
        if (StringUtils.isBlank(discountPrice)) {
            order.setStandy1(totalAmount);
        } else {
            discountPrice = Math.round(Double.valueOf(discountPrice))+"";
            order.setStandy1(discountPrice);
        }
        String orderNo = MakeOrderNum.getMakeOrderNum().makeOrderNum(null);
        order.setOrderNo(orderNo);
        String fullAddress = alRegionService.getFullAddress(areaId, address);
        order.setAddress1(fullAddress);// 完整的收货地址
        order.setAddress2(address);// 详细的收货地址
        // 4、数据库新增订单及订单项数据.
        boolean flag = this.insert(order);
        if (flag) {
            // 4.1、生成订单明细.
            BusiOrderItem orderItem = new BusiOrderItem();
            String idSql = "SELECT (SEQ_BUSI_ORDER_ITEM.NEXTVAL) ITEMID FROM DUAL";
            Map<String, Object> orderItemIdResultMap = jdbcTemplate.queryForMap(idSql);
            Object itemId = orderItemIdResultMap.get("itemid");
            orderItem.setId(itemId.toString());
            orderItem.setProdId(productId);
            orderItem.setCategoryName(null != category ? category.getZhName() : "");
            orderItem.setOrderId(id.toString());
            orderItem.setProdName(busiProduct.getZhName());
            String totalPrice = null;
            String productPrice = busiProduct.getPrice();
            if (StringUtils.isNotBlank(productPrice) && StringUtils.isNotBlank(sum)) {
                BigDecimal prodPrice = new BigDecimal(productPrice);
                BigDecimal prodSum = new BigDecimal(sum);
                totalPrice = prodPrice.multiply(prodSum).toString();
            }
            orderItem.setTotalPrice(totalPrice);
            orderItem.setStandy1(busiProduct.getImgUrl());
            orderItem.setStandy2(busiProduct.getProdDesc());
            orderItem.setStandy3(Dict.YesOrNo.Yes.getCode());
            orderItem.setProdPrice(busiProduct.getPrice());
            orderItem.setSum(sum);
            busiOrderItemService.insert(orderItem);
        } else {
            if (logger.isDebugEnabled()) {
                logger.info("From:[ProductDetail]-[订单生成失败!]");
            }
        }
        String requestBody = ISPaymentRequest.genPayRequestMessage(orderNo, busiProduct.getZhName(),"WS"+phoneNo, order.getStandy1());
        logger.info(String.format("生成的目标报文为:%s", requestBody));
        return requestBody;
    }
}
